/* 商品详情页逻辑 */
class ProductDetailManager {
    constructor() {
        this.productId = null;
        this.product = null;
        this.currentQuantity = 1;
        this.currentDiscount = 0;
        this.reviews = [];
        this.averageRating = 0;
        this.reviewCount = 0;
        this.currentTab = 'reviews';
        this.init();
    }

    init() {
        this.getProductIdFromURL();
        this.bindEvents();
        this.loadProductDetail();
        // 延迟更新认证UI，确保认证管理器完全加载
        setTimeout(() => {
            this.updateAuthUI();
            // 检查URL参数，如果需要显示评价模态框
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('review') === 'true') {
                setTimeout(() => {
                    this.showReviewModal();
                }, 500);
            }
        }, 100);
    }

    getProductIdFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        this.productId = urlParams.get('id');
        
        console.log('从URL获取商品ID:', this.productId);
        
        if (!this.productId) {
            console.error('商品ID不存在');
            this.showError('商品ID不存在');
            return;
        }
    }

    toggleUserMenu() {
        const dropdown = document.getElementById('userDropdown');
        dropdown.classList.toggle('show');
    }

    updateAuthUI() {
        console.log('开始更新认证UI状态');
        
        // 检查认证管理器是否存在
        if (!window.authManager) {
            console.warn('认证管理器尚未初始化，稍后重试');
            // 延迟重试
            setTimeout(() => {
                if (window.authManager) {
                    this.updateAuthUI();
                }
            }, 500);
            return;
        }
        
        // 检查认证状态
        const isAuthenticated = window.authManager.isAuthenticated && window.authManager.isAuthenticated();
        console.log('认证状态:', isAuthenticated);
        
        if (isAuthenticated) {
            const currentUser = JSON.parse(localStorage.getItem('currentUser'));
            console.log('当前用户:', currentUser);
            
            if (currentUser) {
                const userName = document.getElementById('userName');
                const loginLink = document.getElementById('loginLink');
                const registerLink = document.getElementById('registerLink');
                const profileLink = document.getElementById('profileLink');
                const ordersLink = document.getElementById('ordersLink');
                const logoutLink = document.getElementById('logoutLink');
                
                if (userName) userName.textContent = currentUser.username;
                if (loginLink) loginLink.style.display = 'none';
                if (registerLink) registerLink.style.display = 'none';
                if (profileLink) profileLink.style.display = 'block';
                if (ordersLink) ordersLink.style.display = 'block';
                if (logoutLink) logoutLink.style.display = 'block';
                
                console.log('已登录用户界面更新完成');
            }
        } else {
            const userName = document.getElementById('userName');
            const loginLink = document.getElementById('loginLink');
            const registerLink = document.getElementById('registerLink');
            const profileLink = document.getElementById('profileLink');
            const ordersLink = document.getElementById('ordersLink');
            const logoutLink = document.getElementById('logoutLink');
            
            if (userName) userName.textContent = '登录';
            if (loginLink) loginLink.style.display = 'block';
            if (registerLink) registerLink.style.display = 'block';
            if (profileLink) profileLink.style.display = 'none';
            if (ordersLink) ordersLink.style.display = 'none';
            if (logoutLink) logoutLink.style.display = 'none';
            
            console.log('未登录用户界面更新完成');
        }
    }

    bindEvents() {
        // 数量控制
        document.getElementById('decreaseQuantity').addEventListener('click', () => {
            if (this.currentQuantity > 1) {
                this.currentQuantity--;
                document.getElementById('quantity').value = this.currentQuantity;
            }
        });

        document.getElementById('increaseQuantity').addEventListener('click', () => {
            if (this.currentQuantity < 99) {
                this.currentQuantity++;
                document.getElementById('quantity').value = this.currentQuantity;
            }
        });

        document.getElementById('quantity').addEventListener('change', (e) => {
            const value = parseInt(e.target.value);
            if (value >= 1 && value <= 99) {
                this.currentQuantity = value;
            } else {
                e.target.value = this.currentQuantity;
            }
        });

        // 购买操作（只在元素存在时绑定）
        const addToCartBtn = document.getElementById('addToCartBtn');
        if (addToCartBtn) {
            addToCartBtn.addEventListener('click', this.addToCart.bind(this));
        }
        
        const buyNowBtn = document.getElementById('buyNowBtn');
        if (buyNowBtn) {
            buyNowBtn.addEventListener('click', this.buyNow.bind(this));
        }
        
        const playGameBtn = document.getElementById('playGameBtn');
        if (playGameBtn) {
            playGameBtn.addEventListener('click', this.playDiscountGame.bind(this));
        }

        // 用户菜单事件（只在元素存在时绑定）
        const userBtn = document.getElementById('userBtn');
        if (userBtn) {
            userBtn.addEventListener('click', this.toggleUserMenu.bind(this));
        }
        const loginLink = document.getElementById('loginLink');
        if (loginLink) {
            loginLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (window.authManager && window.authManager.showAuthModal) {
                    window.authManager.showAuthModal('login');
                }
            });
        }
        
        const registerLink = document.getElementById('registerLink');
        if (registerLink) {
            registerLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (window.authManager && window.authManager.showAuthModal) {
                    window.authManager.showAuthModal('register');
                }
            });
        }
        
        const logoutLink = document.getElementById('logoutLink');
        if (logoutLink) {
            logoutLink.addEventListener('click', (e) => {
                e.preventDefault();
                if (window.authManager && window.authManager.logout) {
                    window.authManager.logout();
                    this.updateAuthUI();
                }
            });
        }

        // 标签页切换
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.switchTab(e.target.dataset.tab);
            });
        });

        // 评价筛选（只在元素存在时绑定）
        const reviewFilter = document.getElementById('reviewFilter');
        if (reviewFilter) {
            reviewFilter.addEventListener('change', this.filterReviews.bind(this));
        }
        
        const reviewSort = document.getElementById('reviewSort');
        if (reviewSort) {
            reviewSort.addEventListener('change', this.sortReviews.bind(this));
        }

        // 图片放大（只在元素存在时绑定）
        const mainProductImage = document.getElementById('mainProductImage');
        if (mainProductImage) {
            mainProductImage.addEventListener('click', this.showImageModal.bind(this));
        }
        
        const closeImageModal = document.getElementById('closeImageModal');
        if (closeImageModal) {
            closeImageModal.addEventListener('click', this.hideImageModal.bind(this));
        }

        // 评价模态框
        const closeReviewModal = document.getElementById('closeReviewModal');
        if (closeReviewModal) {
            closeReviewModal.addEventListener('click', () => this.hideReviewModal());
        }
        const reviewForm = document.getElementById('reviewForm');
        if (reviewForm) {
            reviewForm.addEventListener('submit', (e) => this.submitReview(e));
        }

        // 评分输入
        this.bindRatingInputs();
    }

    async loadProductDetail() {
        try {
            this.showLoading(true);
            
            // 使用真实API调用
            console.log('开始加载商品详情，商品ID:', this.productId);
            const result = await api.getProductDetail(this.productId);
            console.log('API响应:', result);
            
            if (result.success) {
                this.product = result.data;
                console.log('商品数据:', this.product);
                this.renderProductDetail();
            } else {
                this.showError(result.error);
            }
            
        } catch (error) {
            console.error('加载商品详情失败:', error);
            this.showError('加载商品详情失败');
        } finally {
            this.showLoading(false);
        }
    }

    async getMockProductDetail(productId) {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 500));
        
        const mockProducts = {
            'F001': {
                id: 'F001',
                name: '东北大米',
                price: 115.3,
                originalPrice: 138.0,
                category: 'Food',
                location: '黑龙江省哈尔滨市五常市民乐朝鲜族乡振兴村',
                merchant: '五常大米专营店',
                description: '优质东北大米，粒粒饱满，口感香甜，营养丰富。采用传统种植工艺，无农药残留，是家庭餐桌的理想选择。',
                images: [
                    'https://via.placeholder.com/600x400?text=东北大米主图',
                    'https://via.placeholder.com/600x400?text=东北大米细节1',
                    'https://via.placeholder.com/600x400?text=东北大米细节2',
                    'https://via.placeholder.com/600x400?text=东北大米包装'
                ],
                specifications: {
                    '产地': '黑龙江省五常市',
                    '品种': '稻花香',
                    '净重': '5kg',
                    '保质期': '12个月',
                    '储存方式': '阴凉干燥处',
                    '包装': '真空包装'
                },
                averageRating: 4.5,
                reviewCount: 128
            },
            'F002': {
                id: 'F002',
                name: '山东小麦粉',
                price: 283.6,
                originalPrice: 320.0,
                category: 'Food',
                location: '山东省德州市夏津县银城街道后赵庄村',
                merchant: '山东面粉厂',
                description: '精选山东优质小麦，采用现代制粉工艺，粉质细腻，制作面食口感佳。',
                images: [
                    'https://via.placeholder.com/600x400?text=山东小麦粉主图',
                    'https://via.placeholder.com/600x400?text=山东小麦粉细节1',
                    'https://via.placeholder.com/600x400?text=山东小麦粉细节2'
                ],
                specifications: {
                    '产地': '山东省德州市',
                    '品种': '优质小麦',
                    '净重': '10kg',
                    '保质期': '6个月',
                    '储存方式': '阴凉干燥处',
                    '包装': '食品级包装'
                },
                averageRating: 4.2,
                reviewCount: 89
            }
        };

        const product = mockProducts[productId];
        if (product) {
            return { success: true, data: product };
        } else {
            return { success: false, error: '商品不存在' };
        }
    }

    renderProductDetail() {
        if (!this.product) {
            console.error('商品数据为空，无法渲染');
            return;
        }

        console.log('开始渲染商品详情:', this.product);

        // 更新基本信息
        const productTitle = document.getElementById('productTitle');
        const productPrice = document.getElementById('productPrice');
        const productId = document.getElementById('productId');
        const productLocation = document.getElementById('productLocation');
        const productCategory = document.getElementById('productCategory');
        const productMerchant = document.getElementById('productMerchant');
        const productDescription = document.getElementById('productDescription');

        if (productTitle) productTitle.textContent = this.product.name;
        if (productPrice) productPrice.textContent = `¥${this.product.price.toFixed(2)}`;
        if (productId) productId.textContent = this.product.id;
        if (productLocation) productLocation.textContent = this.product.location;
        if (productCategory) productCategory.textContent = this.getCategoryName(this.product.category);
        if (productMerchant) productMerchant.textContent = this.product.merchant_id;
        if (productDescription) {
            // 使用innerHTML支持换行，并美化显示
            const description = this.product.description || '暂无商品描述';
            // 将逗号、句号等标点后的空格转换为换行，使文本更易读
            const formattedDescription = description
                .replace(/,/g, '，') // 统一使用中文逗号
                .replace(/\./g, '。') // 统一使用中文句号
                .replace(/，\s*/g, '，') // 去除中文逗号后的空格
                .replace(/。\s*/g, '。') // 去除中文句号后的空格
                .replace(/（/g, '（') // 统一使用中文括号
                .replace(/）/g, '）');
            productDescription.textContent = formattedDescription;
        }

        console.log('基本信息更新完成');

        // 更新价格信息
        if (this.product.originalPrice && this.product.originalPrice > this.product.price) {
            const discount = ((this.product.originalPrice - this.product.price) / this.product.originalPrice * 100).toFixed(1);
            document.getElementById('originalPrice').style.display = 'block';
            document.getElementById('originalPrice').querySelector('.price-value').textContent = `¥${this.product.originalPrice.toFixed(2)}`;
            document.getElementById('discountBadge').style.display = 'block';
            document.getElementById('discountPercent').textContent = `${discount}% OFF`;
        }

        // 更新图片
        this.renderProductImages();

        // 更新规格信息
        this.renderSpecifications();

        // 更新面包屑
        document.getElementById('categoryLink').textContent = this.getCategoryName(this.product.category);
        document.getElementById('categoryLink').href = `products.html?category=${this.product.category}`;
        document.getElementById('currentProduct').textContent = this.product.name;

        // 加载评价数据
        this.loadReviews();
    }

    renderProductImages() {
        const mainImage = document.getElementById('mainProductImage');
        const thumbnailContainer = document.getElementById('thumbnailImages');

        if (this.product.images && this.product.images.length > 0) {
            mainImage.src = this.product.images[0];
            mainImage.alt = this.product.name;

            thumbnailContainer.innerHTML = this.product.images.map((image, index) => `
                <div class="thumbnail-item ${index === 0 ? 'active' : ''}" data-image="${image}">
                    <img src="${image}" alt="${this.product.name}">
                </div>
            `).join('');

            // 绑定缩略图点击事件
            thumbnailContainer.querySelectorAll('.thumbnail-item').forEach(item => {
                item.addEventListener('click', () => {
                    const imageSrc = item.dataset.image;
                    mainImage.src = imageSrc;
                    
                    // 更新活动状态
                    thumbnailContainer.querySelectorAll('.thumbnail-item').forEach(i => i.classList.remove('active'));
                    item.classList.add('active');
                });
            });
        }
    }

    renderSpecifications() {
        const specTableBody = document.getElementById('specTableBody');
        
        if (this.product.specifications) {
            specTableBody.innerHTML = Object.entries(this.product.specifications).map(([key, value]) => `
                <tr>
                    <td class="spec-label">${key}</td>
                    <td class="spec-value">${value}</td>
                </tr>
            `).join('');
        }
    }

    async loadReviews() {
        try {
            if (!this.productId) {
                console.warn('商品ID不存在，无法加载评价');
                return;
            }
            
            console.log('开始加载商品评价，商品ID:', this.productId);
            const result = await window.api.getProductReviews(this.productId);
            console.log('评价API响应:', result);
            
            if (result.success) {
                this.reviews = result.data.reviews || [];
                this.averageRating = result.data.average_rating || 0;
                this.reviewCount = result.data.review_count || 0;
                
                console.log(`加载到 ${this.reviewCount} 条评价，平均评分: ${this.averageRating}`);
                console.log('评价数据:', this.reviews);
                
                this.renderReviews();
                this.renderRatingSummary();
            } else {
                console.error('加载评价失败:', result.error);
                this.reviews = [];
                this.averageRating = 0;
                this.reviewCount = 0;
                this.renderReviews();
                this.renderRatingSummary();
            }
        } catch (error) {
            console.error('加载评价失败:', error);
            this.reviews = [];
            this.averageRating = 0;
            this.reviewCount = 0;
            this.renderReviews();
            this.renderRatingSummary();
        }
    }
    

    renderRatingSummary() {
        const averageRating = this.averageRating || 0;
        const reviewCount = this.reviewCount || 0;

        const avgElement = document.getElementById('averageRating');
        if (avgElement) avgElement.textContent = averageRating.toFixed(1);
        
        const countElement = document.getElementById('reviewCount');
        if (countElement) countElement.textContent = `(${reviewCount}条评价)`;
        
        // 渲染星级评分
        const starsContainer = document.getElementById('ratingStars');
        if (starsContainer) {
            starsContainer.innerHTML = this.generateStars(averageRating);
        }

        // 渲染评分分布
        const breakdown = this.calculateRatingBreakdown();
        const breakdownContainer = document.getElementById('ratingBreakdown');
        if (breakdownContainer) {
            breakdownContainer.innerHTML = Object.entries(breakdown).map(([rating, count]) => `
                <div class="rating-bar">
                    <span class="rating-label">${rating}星</span>
                    <div class="rating-progress">
                        <div class="progress-bar" style="width: ${reviewCount > 0 ? (count / reviewCount * 100) : 0}%"></div>
                    </div>
                    <span class="rating-count">${count}</span>
                </div>
            `).join('');
        }
    }

    calculateRatingBreakdown() {
        const breakdown = { 5: 0, 4: 0, 3: 0, 2: 0, 1: 0 };
        this.reviews.forEach(review => {
            // 使用商品评分进行统计
            const rating = review.product_rating || review.rating || 0;
            if (rating >= 1 && rating <= 5) {
                breakdown[rating]++;
            }
        });
        return breakdown;
    }

    generateStars(rating) {
        const fullStars = Math.floor(rating);
        const hasHalfStar = rating % 1 >= 0.5;
        const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);

        let stars = '';
        for (let i = 0; i < fullStars; i++) {
            stars += '<i class="fas fa-star"></i>';
        }
        if (hasHalfStar) {
            stars += '<i class="fas fa-star-half-alt"></i>';
        }
        for (let i = 0; i < emptyStars; i++) {
            stars += '<i class="far fa-star"></i>';
        }
        return stars;
    }

    renderReviews() {
        const reviewsList = document.getElementById('reviewsList');
        if (!reviewsList) return;
        
        if (this.reviews.length === 0) {
            reviewsList.innerHTML = '<div class="empty-reviews"><p>暂无评价，快来发表第一条评价吧！</p></div>';
            return;
        }
        
        reviewsList.innerHTML = this.reviews.map(review => {
            const reviewDate = new Date(review.review_date).toLocaleDateString();
            const productRating = review.product_rating || review.rating || 0;
            const merchantRating = review.merchant_rating || 0;
            const logisticsRating = review.logistics_rating || 0;
            
            // 显示商家回复
            const merchantReplyHtml = review.merchant_reply ? `
                <div class="merchant-reply">
                    <div class="merchant-reply-header">
                        <i class="fas fa-store"></i>
                        <span class="merchant-label">商家回复</span>
                        <span class="reply-date">${new Date(review.merchant_reply.timestamp || review.merchant_reply.review_date).toLocaleDateString()}</span>
                    </div>
                    <div class="merchant-reply-content">${review.merchant_reply.text || review.merchant_reply.content || ''}</div>
                </div>
            ` : '';
            
            // 显示回复列表
            const repliesHtml = review.replies && review.replies.length > 0 ? `
                <div class="review-replies">
                    ${review.replies.map(reply => `
                        <div class="reply-item">
                            <span class="reply-user">${reply.customer_id || reply.user_id || '匿名用户'}</span>
                            <span class="reply-content">${reply.content || reply.text || ''}</span>
                            <span class="reply-date">${new Date(reply.reply_date || reply.timestamp).toLocaleDateString()}</span>
                        </div>
                    `).join('')}
                </div>
            ` : '';
            
            return `
                <div class="review-item">
                    <div class="review-header">
                        <div class="review-user">
                            <span class="user-name">${review.customer_id || '匿名用户'}</span>
                            <div class="review-ratings">
                                <span class="rating-item">商品: ${this.generateStars(productRating)}</span>
                                <span class="rating-item">商家: ${this.generateStars(merchantRating)}</span>
                                <span class="rating-item">物流: ${this.generateStars(logisticsRating)}</span>
                            </div>
                        </div>
                        <div class="review-date">${reviewDate}</div>
                    </div>
                    <div class="review-content">
                        <p>${review.comment || ''}</p>
                    </div>
                    ${merchantReplyHtml}
                    ${repliesHtml}
                    <div class="review-footer">
                        <button class="helpful-btn" onclick="productDetailManager.likeReview('${review.review_id}')">
                            <i class="fas fa-thumbs-up"></i>
                            有用 (${review.likes || 0})
                        </button>
                    </div>
                </div>
            `;
        }).join('');
    }

    filterReviews() {
        const filter = document.getElementById('reviewFilter').value;
        let filteredReviews = this.reviews;

        if (filter === 'all') {
            filteredReviews = this.reviews;
        } else if (filter === 'good') {
            // 好评：平均评分 >= 4
            filteredReviews = this.reviews.filter(review => {
                const avg = this.calculateAverageRating(review);
                return avg >= 4;
            });
        } else if (filter === 'medium') {
            // 中评：平均评分 2 < avg < 4
            filteredReviews = this.reviews.filter(review => {
                const avg = this.calculateAverageRating(review);
                return avg > 2 && avg < 4;
            });
        } else if (filter === 'bad') {
            // 差评：平均评分 <= 2
            filteredReviews = this.reviews.filter(review => {
                const avg = this.calculateAverageRating(review);
                return avg <= 2;
            });
        } else {
            // 按星级筛选
            const rating = parseInt(filter);
            filteredReviews = this.reviews.filter(review => {
                const productRating = review.product_rating || review.rating || 0;
                return productRating === rating;
            });
        }

        this.renderFilteredReviews(filteredReviews);
    }
    
    calculateAverageRating(review) {
        // 计算平均评分（商品、商家、物流的平均值）
        const productRating = review.product_rating || review.rating || 0;
        const merchantRating = review.merchant_rating || 0;
        const logisticsRating = review.logistics_rating || 0;
        
        // 如果有所有三种评分，取平均值
        if (merchantRating > 0 && logisticsRating > 0) {
            return (productRating + merchantRating + logisticsRating) / 3.0;
        }
        // 否则只使用商品评分
        return productRating;
    }

    sortReviews() {
        const sort = document.getElementById('reviewSort').value;
        let sortedReviews = [...this.reviews];

        switch (sort) {
            case 'latest':
                sortedReviews.sort((a, b) => new Date(b.review_date) - new Date(a.review_date));
                break;
            case 'hottest':
                // 最热：点赞数 + 回复数
                sortedReviews.sort((a, b) => {
                    const aHot = (a.likes || 0) + (a.replies ? a.replies.length : 0);
                    const bHot = (b.likes || 0) + (b.replies ? b.replies.length : 0);
                    return bHot - aHot;
                });
                break;
            case 'rating':
                // 按平均评分排序
                sortedReviews.sort((a, b) => {
                    const aAvg = this.calculateAverageRating(b);
                    const bAvg = this.calculateAverageRating(a);
                    return bAvg - aAvg;
                });
                break;
        }

        this.renderFilteredReviews(sortedReviews);
    }

    renderFilteredReviews(reviews) {
        const reviewsList = document.getElementById('reviewsList');
        if (!reviewsList) return;
        
        if (reviews.length === 0) {
            reviewsList.innerHTML = '<div class="empty-reviews"><p>暂无符合条件的评价</p></div>';
            return;
        }
        
        reviewsList.innerHTML = reviews.map(review => {
            const reviewDate = new Date(review.review_date).toLocaleDateString();
            const productRating = review.product_rating || review.rating || 0;
            const merchantRating = review.merchant_rating || 0;
            const logisticsRating = review.logistics_rating || 0;
            
            // 显示商家回复
            const merchantReplyHtml = review.merchant_reply ? `
                <div class="merchant-reply">
                    <div class="merchant-reply-header">
                        <i class="fas fa-store"></i>
                        <span class="merchant-label">商家回复</span>
                        <span class="reply-date">${new Date(review.merchant_reply.timestamp || review.merchant_reply.review_date).toLocaleDateString()}</span>
                    </div>
                    <div class="merchant-reply-content">${review.merchant_reply.text || review.merchant_reply.content || ''}</div>
                </div>
            ` : '';
            
            // 显示回复列表
            const repliesHtml = review.replies && review.replies.length > 0 ? `
                <div class="review-replies">
                    ${review.replies.map(reply => `
                        <div class="reply-item">
                            <span class="reply-user">${reply.customer_id || reply.user_id || '匿名用户'}</span>
                            <span class="reply-content">${reply.content || reply.text || ''}</span>
                            <span class="reply-date">${new Date(reply.reply_date || reply.timestamp).toLocaleDateString()}</span>
                        </div>
                    `).join('')}
                </div>
            ` : '';
            
            return `
                <div class="review-item">
                    <div class="review-header">
                        <div class="review-user">
                            <span class="user-name">${review.customer_id || '匿名用户'}</span>
                            <div class="review-ratings">
                                <span class="rating-item">商品: ${this.generateStars(productRating)}</span>
                                <span class="rating-item">商家: ${this.generateStars(merchantRating)}</span>
                                <span class="rating-item">物流: ${this.generateStars(logisticsRating)}</span>
                            </div>
                        </div>
                        <div class="review-date">${reviewDate}</div>
                    </div>
                    <div class="review-content">
                        <p>${review.comment || ''}</p>
                    </div>
                    ${merchantReplyHtml}
                    ${repliesHtml}
                    <div class="review-footer">
                        <button class="helpful-btn" onclick="productDetailManager.likeReview('${review.review_id}')">
                            <i class="fas fa-thumbs-up"></i>
                            有用 (${review.likes || 0})
                        </button>
                    </div>
                </div>
            `;
        }).join('');
    }


    switchTab(tabName) {
        // 更新标签按钮状态
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

        // 更新标签内容
        document.querySelectorAll('.tab-panel').forEach(panel => {
            panel.classList.remove('active');
        });
        document.getElementById(`${tabName}Tab`).classList.add('active');

        this.currentTab = tabName;
    }

    addToCart() {
        console.log('尝试添加到购物车');
        
        // 检查认证管理器是否存在
        if (!window.authManager) {
            console.warn('认证管理器尚未初始化');
            alert('系统错误，请刷新页面重试');
            return;
        }
        
        // 检查认证状态
        const isAuthenticated = window.authManager.isAuthenticated && window.authManager.isAuthenticated();
        console.log('认证状态:', isAuthenticated);
        
        if (!isAuthenticated) {
            console.log('用户未登录，显示登录模态框');
            if (window.authManager.showAuthModal) {
                window.authManager.showAuthModal('login');
            }
            return;
        }

        console.log('用户已登录，添加到购物车');
        if (window.cartManager) {
            window.cartManager.addToCart(
                this.product.id,
                this.product.name,
                this.product.price,
                this.currentQuantity
            );
            console.log('商品已添加到购物车');
        } else {
            console.error('购物车管理器不存在');
            alert('购物车功能暂时不可用');
        }
    }

    buyNow() {
        if (!window.authManager) {
            alert('系统错误，请刷新页面重试');
            return;
        }
        
        const isAuthenticated = window.authManager.isAuthenticated && window.authManager.isAuthenticated();
        if (!isAuthenticated) {
            if (window.authManager.showAuthModal) {
                window.authManager.showAuthModal('login');
            }
            return;
        }

        // 检查商品数据是否已加载
        if (!this.product) {
            this.showNotification('商品信息加载中，请稍候...', 'error');
            return;
        }

        // 构建订单项数据
        const orderItem = {
            product_id: this.product.id,
            product_name: this.product.name,
            price: this.product.price,
            quantity: this.currentQuantity,
            selected: true,
            image: this.product.image || (this.product.images && this.product.images[0]) || '',
            category: this.product.category,
            location: this.product.location || '',
            merchant_id: this.product.merchant_id || ''
        };

        // 保存到localStorage，供结算页面使用
        localStorage.setItem('checkoutItems', JSON.stringify([orderItem]));
        console.log('立即购买商品信息已保存:', orderItem);

        // 跳转到结算页面
        window.location.href = 'checkout.html';
    }

    playDiscountGame() {
        if (!window.authManager) {
            alert('系统错误，请刷新页面重试');
            return;
        }
        
        const isAuthenticated = window.authManager.isAuthenticated && window.authManager.isAuthenticated();
        if (!isAuthenticated) {
            if (window.authManager.showAuthModal) {
                window.authManager.showAuthModal('login');
            }
            return;
        }

        if (window.discountGame) {
            window.discountGame.showGameModal();
        }
    }

    showImageModal() {
        const modal = document.getElementById('imageModal');
        const modalImage = document.getElementById('modalImage');
        const mainImage = document.getElementById('mainProductImage');
        
        modalImage.src = mainImage.src;
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
    }

    hideImageModal() {
        const modal = document.getElementById('imageModal');
        modal.style.display = 'none';
        document.body.style.overflow = 'auto';
    }

    bindRatingInputs() {
        // 为三个评分输入框绑定事件
        ['productRating', 'merchantRating', 'logisticsRating'].forEach(ratingId => {
            setTimeout(() => {
                const container = document.getElementById(ratingId);
                if (!container) {
                    console.warn(`未找到${ratingId}元素`);
                    return;
                }
                
                // 直接为每个星星绑定事件
                const stars = container.querySelectorAll('.fas.fa-star, .far.fa-star');
                stars.forEach((star, index) => {
                    // 移除可能存在的旧监听器
                    const newStar = star.cloneNode(true);
                    star.parentNode.replaceChild(newStar, star);
                    
                    const rating = index + 1;
                    newStar.addEventListener('click', (e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        this.setRating(container, rating);
                        console.log(`设置${ratingId}评分为:`, rating);
                    });
                    
                    newStar.addEventListener('mouseenter', () => {
                        this.highlightStars(container, rating);
                    });
                });
                
                container.addEventListener('mouseleave', () => {
                    this.resetStars(container);
                });
                
                console.log(`${ratingId}评分输入事件已绑定`);
            }, 100);
        });
    }
    
    showReviewModal() {
        const modal = document.getElementById('reviewModal');
        if (modal) {
            modal.style.display = 'block';
            document.body.style.overflow = 'hidden';
            // 重新绑定评分事件
            this.bindRatingInputs();
        }
    }
    
    hideReviewModal() {
        const modal = document.getElementById('reviewModal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
            document.getElementById('reviewForm').reset();
            // 重置所有评分
            ['productRating', 'merchantRating', 'logisticsRating'].forEach(ratingId => {
                const container = document.getElementById(ratingId);
                if (container) {
                    container.dataset.rating = '0';
                    this.resetStars(container);
                }
            });
        }
    }
    
    async likeReview(reviewId) {
        try {
            const result = await window.api.likeReview(reviewId);
            if (result.success) {
                // 更新本地评价数据
                const review = this.reviews.find(r => r.review_id === reviewId);
                if (review) {
                    review.likes = result.data.likes;
                    this.renderReviews();
                }
            }
        } catch (error) {
            console.error('点赞失败:', error);
        }
    }

    setRating(container, rating) {
        container.dataset.rating = rating;
        this.updateStars(container, rating);
    }

    highlightStars(container, rating) {
        this.updateStars(container, rating, true);
    }

    resetStars(container) {
        const currentRating = parseInt(container.dataset.rating) || 0;
        this.updateStars(container, currentRating);
    }

    updateStars(container, rating, highlight = false) {
        const stars = container.querySelectorAll('.fas.fa-star, .far.fa-star');
        stars.forEach((star, index) => {
            if (index < rating) {
                star.className = 'fas fa-star';
                star.style.color = highlight ? '#ffa500' : '#ffd700';
            } else {
                star.className = 'far fa-star';
                star.style.color = '#ddd';
            }
        });
    }

    async submitReview(e) {
        e.preventDefault();
        
        if (!window.authManager) {
            alert('系统错误，请刷新页面重试');
            return;
        }
        
        const isAuthenticated = window.authManager.isAuthenticated && window.authManager.isAuthenticated();
        if (!isAuthenticated) {
            if (window.authManager.showAuthModal) {
                window.authManager.showAuthModal('login');
            }
            return;
        }

        const productRating = parseInt(document.getElementById('productRating').dataset.rating) || 0;
        const merchantRating = parseInt(document.getElementById('merchantRating').dataset.rating) || 0;
        const logisticsRating = parseInt(document.getElementById('logisticsRating').dataset.rating) || 0;
        const reviewText = document.getElementById('reviewText').value.trim();

        if (productRating === 0) {
            this.showNotification('请选择商品评分', 'error');
            return;
        }

        if (merchantRating === 0) {
            this.showNotification('请选择商家评分', 'error');
            return;
        }

        if (logisticsRating === 0) {
            this.showNotification('请选择物流评分', 'error');
            return;
        }

        if (!reviewText) {
            this.showNotification('请输入评价内容', 'error');
            return;
        }

        try {
            const result = await window.api.createReview({
                product_id: this.productId,
                product_rating: productRating,
                merchant_rating: merchantRating,
                logistics_rating: logisticsRating,
                comment: reviewText
            });
            
            if (result.success) {
                this.showNotification('评价提交成功！', 'success');
                this.hideReviewModal();
                // 重新加载评价列表
                await this.loadReviews();
            } else {
                this.showNotification('评价提交失败: ' + result.error, 'error');
            }
        } catch (error) {
            console.error('提交评价失败:', error);
            this.showNotification('评价提交失败: ' + error.message, 'error');
        }
    }


    getCategoryName(category) {
        const categoryNames = {
            'Food': '食品',
            'Clothing': '服装',
            'Book': '图书',
            'Electronic Products': '电子产品',
            'Daily product': '日用品'
        };
        return categoryNames[category] || category;
    }

    showLoading(show) {
        const loading = document.getElementById('loading');
        if (loading) {
            loading.style.display = show ? 'flex' : 'none';
        }
    }

    hideLoading() {
        this.showLoading(false);
    }

    renderProductImages() {
        if (!this.product) return;
        
        const mainImage = document.getElementById('mainProductImage');
        const thumbnailContainer = document.getElementById('thumbnailImages');
        
        if (mainImage) {
            mainImage.src = this.product.image || 'https://via.placeholder.com/600x400?text=商品图片';
            mainImage.alt = this.product.name;
        }
        
        if (thumbnailContainer) {
            thumbnailContainer.innerHTML = '';
            const images = this.product.images || [this.product.image];
            images.forEach((image, index) => {
                const thumbnail = document.createElement('img');
                thumbnail.src = image;
                thumbnail.alt = `${this.product.name} ${index + 1}`;
                thumbnail.className = index === 0 ? 'thumbnail active' : 'thumbnail';
                thumbnail.addEventListener('click', () => {
                    mainImage.src = image;
                    document.querySelectorAll('.thumbnail').forEach(t => t.classList.remove('active'));
                    thumbnail.classList.add('active');
                });
                thumbnailContainer.appendChild(thumbnail);
            });
        }
    }

    renderSpecifications() {
        if (!this.product) return;
        
        const specsContainer = document.getElementById('specifications');
        if (specsContainer) {
            const specs = this.product.specifications || [
                { name: '产地', value: this.product.location },
                { name: '分类', value: this.getCategoryName(this.product.category) },
                { name: '商家', value: this.product.merchant_id }
            ];
            
            specsContainer.innerHTML = specs.map(spec => 
                `<div class="spec-item">
                    <span class="spec-name">${spec.name}：</span>
                    <span class="spec-value">${spec.value}</span>
                </div>`
            ).join('');
        }
    }



    playDiscountGame() {
        if (window.gameManager) {
            window.gameManager.showGameModal();
        }
    }



    showImageModal() {
        // 显示图片放大模态框
        const modal = document.getElementById('imageModal');
        if (modal) {
            modal.style.display = 'flex';
        }
    }

    hideImageModal() {
        // 隐藏图片放大模态框
        const modal = document.getElementById('imageModal');
        if (modal) {
            modal.style.display = 'none';
        }
    }


    showError(message) {
        this.showNotification(message, 'error');
        setTimeout(() => {
            window.location.href = 'index.html';
        }, 2000);
    }

    showNotification(message, type = 'info') {
        if (window.authManager && window.authManager.showNotification) {
            window.authManager.showNotification(message, type);
        }
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('商品详情页开始初始化');
    
    // 确保所有依赖的模块都已加载
    const initProductDetail = () => {
        if (window.api && window.authManager && window.cartManager) {
            window.productDetailManager = new ProductDetailManager();
            console.log('商品详情页初始化完成');
        } else {
            console.log('等待依赖模块加载...');
            setTimeout(initProductDetail, 100);
        }
    };
    
    // 延迟初始化，确保所有脚本都已加载
    setTimeout(initProductDetail, 200);
});
